// =====================================================
// HomePage - 主页面（三栏布局）
// =====================================================

import { useState, useEffect } from "react";
import { Layout, message } from "antd";
import FeedList from "../components/FeedList";
import ArticleList from "../components/ArticleList";
import ArticleReader from "../components/ArticleReader";
import AIChatPanel from "../components/AIChatPanel";
import Header from "../components/Header";
import ErrorBoundary from "../components/ErrorBoundary";
import type { Feed, Article } from "../types";
import { getFeedList } from "../services/feed";
import { getArticleList } from "../services/article";

const { Sider, Content } = Layout;

interface HomePageProps {
  darkMode: boolean;
  onToggleDarkMode: () => void;
}

export default function HomePage({
  darkMode,
  onToggleDarkMode,
}: HomePageProps) {
  const [feeds, setFeeds] = useState<Feed[]>([]);
  const [articles, setArticles] = useState<Article[]>([]);
  const [selectedFeed, setSelectedFeed] = useState<Feed | null>(null);
  const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [isReading, setIsReading] = useState(false); // 是否处于阅读模式

  // 加载订阅源列表
  const loadFeeds = async () => {
    try {
      const data = await getFeedList();
      setFeeds(data);
    } catch {
      message.error("加载订阅源失败");
    }
  };

  // 加载文章列表
  const loadArticles = async (feedId?: number, currentPage = 1) => {
    setLoading(true);
    console.log("🔍 Loading articles:", { feedId, currentPage }); // 调试日志
    try {
      const params: { page: number; size: number; feed_id?: number } = {
        page: currentPage,
        size: pageSize,
      };

      // 只有当 feedId 有值时才添加到查询参数
      if (feedId !== undefined) {
        params.feed_id = feedId;
      }

      console.log("📤 Request params:", params); // 调试日志
      const data = await getArticleList(params);
      console.log("📥 Response data:", data); // 调试日志
      console.log("📥 Response data.articles:", data.articles); // 新增
      console.log("📥 Response data.total:", data.total); // 新增
      setArticles(data.articles || []);
      setTotal(data.total || 0);
      setPage(currentPage);
    } catch (error) {
      console.error("❌ Load articles error:", error); // 调试日志
      message.error("加载文章失败");
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载
  useEffect(() => {
    loadFeeds();
    loadArticles();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 选择订阅源
  const handleSelectFeed = (feed: Feed | null) => {
    setSelectedFeed(feed);
    setSelectedArticle(null);
    loadArticles(feed?.id);
  };

  // 选择文章
  const handleSelectArticle = (article: Article) => {
    setSelectedArticle(article);
    setIsReading(true); // 进入阅读模式
  };

  // 退出阅读模式
  const handleExitReading = () => {
    setSelectedArticle(null);
    setIsReading(false);
  };

  // 刷新订阅源
  const handleRefreshFeed = () => {
    loadFeeds();
    loadArticles(selectedFeed?.id, page);
  };

  // 刷新文章列表
  const handleRefreshArticles = () => {
    loadArticles(selectedFeed?.id, page);
  };

  return (
    <Layout style={{ height: "95vh", overflow: "hidden" }}>
      {/* 顶部导航栏 */}
      <Header
        darkMode={darkMode}
        onToggleDarkMode={onToggleDarkMode}
        onRefresh={handleRefreshFeed}
      />

      <Layout style={{ height: "calc(100vh - 64px)" }}>
        {/* 左侧：订阅源列表 - 阅读模式时隐藏 */}
        {!isReading && (
          <Sider
            width={260}
            theme={darkMode ? "dark" : "light"}
            style={{
              overflow: "auto",
              borderRight: `1px solid ${darkMode ? "#303030" : "#e8e8e8"}`,
              background: darkMode ? "#141414" : "#fafafa",
            }}
          >
            <FeedList
              feeds={feeds}
              selectedFeed={selectedFeed}
              onSelectFeed={handleSelectFeed}
              onRefresh={loadFeeds}
            />
          </Sider>
        )}

        {/* 中间：文章列表 - 阅读模式时缩小 */}
        <Sider
          width={isReading ? 320 : 500}
          theme="light"
          style={{
            overflow: "auto",
            borderRight: "1px solid #e8e8e8",
            background: "#fff",
          }}
        >
          <ErrorBoundary>
            <ArticleList
              articles={articles}
              selectedArticle={selectedArticle}
              onSelectArticle={handleSelectArticle}
              loading={loading}
              total={total}
              page={page}
              pageSize={pageSize}
              onPageChange={(newPage: number) =>
                loadArticles(selectedFeed?.id, newPage)
              }
              onRefresh={handleRefreshArticles}
            />
          </ErrorBoundary>
        </Sider>

        {/* 右侧：文章阅读器 + AI 聊天面板 */}
        <Layout style={{ flex: 1, overflow: "hidden" }}>
          {/* 文章内容区域 */}
          <Content
            style={{
              overflow: "auto",
              background: "#fff",
              padding: isReading ? "0" : "24px",
              flex: isReading ? "0 0 75%" : "1", // 阅读模式时占 75% 宽度
              borderRight: isReading ? "1px solid #e8e8e8" : "none",
            }}
          >
            <ErrorBoundary>
              <ArticleReader
                article={selectedArticle}
                onRefresh={handleRefreshArticles}
                onBack={isReading ? handleExitReading : undefined}
                isFullScreen={isReading}
              />
            </ErrorBoundary>
          </Content>

          {/* AI 聊天面板 - 阅读模式时显示 */}
          {isReading && (
            <Sider
              width="25%"
              theme="light"
              style={{
                overflow: "hidden",
                background: "#fff",
              }}
            >
              <ErrorBoundary>
                <AIChatPanel article={selectedArticle} />
              </ErrorBoundary>
            </Sider>
          )}
        </Layout>
      </Layout>
    </Layout>
  );
}
